package com.cheung.leetcode.normal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LC13 {

    public static int romanToInt(String s) {
        /**
         * I 1
         * II 2
         * III 3
         * IV 4
         * V 5
         * VI 6
         * VII 7
         * VIII 8
         * IX 9
         * X 10
         * L 50
         * I             1
         * IV 4
         * V             5
         * X             10
         * XL 40
         * L             50
         * XC       90
         * C             100
         * CD 400
         * D             500
         * CM 900
         * M             1000
         */

        Map<String, Integer> hash = new HashMap<>();
        hash.put("I", 1);
        hash.put("IV", 4);
        hash.put("V", 5);
        hash.put("IX", 9);
        hash.put("X", 10);
        hash.put("XL", 40);
        hash.put("L", 50);
        hash.put("XC", 90);
        hash.put("C", 100);
        hash.put("CD", 400);
        hash.put("D", 500);
        hash.put("CM", 900);
        hash.put("M", 1000);

        int index = 0;
        List<String> list = new ArrayList<>();
        while (index < s.length()) {
            // 如果只剩最后一位了
            if (index == s.length() - 1) {
                list.add(s.substring(index));
                index += 1;
            } else {
                // 否则先截取两个字符
                String s2 = s.substring(index, index + 2);
                if (hash.containsKey(s2)) {
                    list.add(s2);
                    index += 2;
                } else {
                    list.add(s.substring(index, index + 1));
                    index += 1;
                }
            }


        }


        Integer num = 0;
        for (String string : list) {
            num += hash.get(string);
        }

        return num;

    }


    public static int romanToIntV2(String s) {
        Map<Character, Integer> hash = new HashMap<>();
        hash.put('I', 1);
        hash.put('V', 5);
        hash.put('X', 10);
        hash.put('L', 50);
        hash.put('C', 100);
        hash.put('D', 500);
        hash.put('M', 1000);

        int num = 0;
        for (int i = 0; i < s.length(); i++) {
            Integer c = hash.get(s.charAt(i));
            if (i == s.length() - 1) {
                num += c;
            } else {
                // 如果前面的小于后面的做减法
                Integer next = hash.get(s.charAt(i + 1));
                if (c < next) {
                    num -= c;
                } else {
                    num += c;
                }
            }
        }

        return num;
    }

    public static void main(String[] args) {
//        System.out.println(romanToIntV2("LVIII"));
        System.out.println(romanToInt("MCMXCIV"));
        System.out.println(romanToIntV2("MCMXCIV"));
    }
}
